package com.dsit.sq;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dsit.sq.mydefineview.LongColorfulProgressBar;
import com.dsit.sq.mydefineview.PullToRefreshBase;
import com.dsit.sq.mydefineview.PullToRefreshScrollView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

/**
 * Created by dsit_dev04 on 2016/10/8.
 */
public class DetailCarDataActivity extends BaseActivity implements OnClickListener {

    private ImageView detailReturnImageView;
    private TextView socDataTextView;
    private TextView socStatusTextView;
    private TextView voltageDataTextView;
    private TextView voltageStatusTextView;
    private TextView dianliuDataTextView;
    private TextView dianliuStatusTextView;
    private TextView tempretureDataTextView;
    private TextView tempretureStatusTextView;
    private LongColorfulProgressBar socProgressBar;
    private LongColorfulProgressBar voltageProgressBar;
    private LongColorfulProgressBar dianliuProgressBar;
    private LongColorfulProgressBar powerBatteryTempProgressBar;
    private PullToRefreshScrollView pullPowerBatteryScrollView;
    private final int battery_soc = 0;// 电池ＳＯＣ
    private final int battery_vol = 1;// 电池电压
    private final int battery_dianliu = 2;//　电池电流
    private final int battery_tempreture = 3;//　电池温度
    private ScrollView powerBatteryScrollView;
    private LinearLayout powerBatteryLinearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detaildata);
        detailReturnImageView = (ImageView) findViewById(R.id.detail_return_button);
        detailReturnImageView.setOnClickListener(this);
        ProtoMsgDispatcher.getInstance().addDataListener(dataListener);



        LayoutInflater inflater = LayoutInflater.from(getApplication());
        powerBatteryLinearLayout =(LinearLayout) inflater.inflate(R.layout.power_battery_layout,null);
        socDataTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.volsoc_data_text);
        socStatusTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.volsoc_status_text);
        voltageDataTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.voltage_data_text);
        voltageStatusTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.voltage_status_text);
        dianliuDataTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.dianliu_data_text);
        dianliuStatusTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.dianliu_status_text);
        tempretureDataTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.tempreture_data_text);
        tempretureStatusTextView = (TextView) powerBatteryLinearLayout.findViewById(R.id.tempreture_status_text);
        socProgressBar = (LongColorfulProgressBar) powerBatteryLinearLayout.findViewById(R.id.soc_status_image);
        voltageProgressBar = (LongColorfulProgressBar) powerBatteryLinearLayout.findViewById(R.id.voltage_status_image);
        dianliuProgressBar = (LongColorfulProgressBar) powerBatteryLinearLayout.findViewById(R.id.dianliu_status_image);
        powerBatteryTempProgressBar = (LongColorfulProgressBar) powerBatteryLinearLayout.findViewById(R.id.power_battery_temp_image);
        pullPowerBatteryScrollView = (PullToRefreshScrollView)findViewById(R.id.power_battery_pullscroll);
        pullPowerBatteryScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
        powerBatteryScrollView = pullPowerBatteryScrollView.getRefreshableView();
        powerBatteryScrollView.setVerticalScrollBarEnabled(false);
        powerBatteryScrollView.addView(powerBatteryLinearLayout);
//        powerBatteryScrollView.addView(createTextView());
        setLastUpdateTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ProtoMsgDispatcher.getInstance().removeDataListener(dataListener);
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            pullPowerBatteryScrollView.onPullDownRefreshComplete();
            setLastUpdateTime();
            super.onPostExecute(result);
        }
    }
    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        pullPowerBatteryScrollView.setLastUpdatedLabel(text);
    }

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("HH:mm:ss");
    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        return mDateFormat.format(new Date(time));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detail_return_button:
                finish();
            default:
                break;
        }
    }

    private DataListener dataListener = new DataListener() {
        @Override
        public void onUpdateData(ProtoMessage msg) {
            if(msg.getActionId().equals("canbus.msg")){
                byte[] data = msg.getContentData();
                Log.i("main_activity", "收到回调");
                String str = new String(data, 0, data.length);
                try {
                    JSONArray array = new JSONArray(str);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = (JSONObject) array.get(i);
                        int id = object.getInt("id");
                        Double value = object.getDouble("value");
                        Bundle bundle = new Bundle();
                        Message message = new Message();
                        message.setData(bundle);
                        bundle.putDouble("value", value);
                        switch (id) {
                            case battery_soc:
                                message.what = battery_soc;
                                mHandler.sendMessage(message);
                                break;
                            case battery_vol:
                                message.what = battery_vol;
                                mHandler.sendMessage(message);
                                break;
                            case battery_dianliu:
                                message.what = battery_dianliu;
                                mHandler.sendMessage(message);
                                break;
                            case battery_tempreture:
                                message.what = battery_tempreture;
                                mHandler.sendMessage(message);
                                break;
                            default:
                                break;
                        }
                        Log.i("data", object.toString());

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message message) {
            try {
                Bundle bundle = new Bundle();
                bundle = message.getData();
                Double data = bundle.getDouble("value");
                switch (message.what) {
                    case battery_soc:
                        socDataTextView.setText(formatDouble(data) + "%");
                        if ((data - 20.0) < 0.00001) {
                            socStatusTextView.setText("过低");
                        } else if ((data - 80.0) > 0.00001) {
                            socStatusTextView.setText("过高");
                        } else {
                            socStatusTextView.setText("正常");
                        }
                        int progress1 = (int) ((float) (data / 102) * 100);
                        socProgressBar.setProgress(progress1);
                        break;
                    case battery_vol:
                        int progress2 = (int) ((float) (data / 1023) * 100);
                        voltageProgressBar.setProgress(progress2);
                        voltageDataTextView.setText(formatDouble(data) + "V");
                        voltageStatusTextView.setText("");
                        break;
                    case battery_dianliu:
                        dianliuDataTextView.setText(formatDouble(data) + "A");
                        dianliuStatusTextView.setText("");
                        data = 1000 + data;
                        int progress3 = (int) ((float) (data / 1638) * 100);
                        dianliuProgressBar.setProgress(progress3);
                        break;
                    case battery_tempreture:
                        if (data == 254.0) {
                            tempretureDataTextView.setText("Init");
                            tempretureStatusTextView.setText("");
                            powerBatteryTempProgressBar.setProgress(0);

                        } else if (data == 255.0) {
                            tempretureDataTextView.setText("Error");
                            tempretureStatusTextView.setText("");
                            powerBatteryTempProgressBar.isAllRed = true;
                            powerBatteryTempProgressBar.setProgress(100);
                            mHandler.sendEmptyMessage(80);
                        } else {
                            data = data * 0.5 - 40;
                            tempretureDataTextView.setText(formatDouble(data) + "℃");
                            if ((data - 45.0) > 0.00001) {
                                tempretureStatusTextView.setText("过高");
                            } else {
                                tempretureStatusTextView.setText("正常");
                            }
                            data = 40 + data;
                            int progress4 = (int) ((float) (data / 126.5) * 100);
                            powerBatteryTempProgressBar.setProgress(progress4);
                        }
                        break;
                    case 80:
                        powerBatteryTempProgressBar.isAllRed = false;
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private String formatDouble(Double data) {
        DecimalFormat format = new DecimalFormat("0.00");
        return format.format(data);
    }
}
